package com.company.cloud.art.modules.mgr.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.art.modules.app.controller.req.ExpoJoinQuery4PageParam;
import com.company.cloud.art.modules.base.entity.ExpoInfo;
import com.company.cloud.art.modules.base.entity.ExpoJoinInfo;
import com.company.cloud.art.modules.base.entity.ExpoJoinProductInfo;
import com.company.cloud.art.modules.base.entity.ExpoSignUpInfo;
import com.company.cloud.art.modules.base.service.ExpoInfoService;
import com.company.cloud.art.modules.base.service.ExpoJoinInfoService;
import com.company.cloud.art.modules.base.service.ExpoJoinProductInfoService;
import com.company.cloud.art.modules.base.service.ExpoSignUpInfoService;
import com.company.cloud.art.modules.cache.models.*;
import com.company.cloud.art.modules.cache.utils.ArtConvertUtils;
import com.company.cloud.art.modules.mgr.controller.req.*;
import com.company.cloud.art.modules.mgr.mapper.ExpoJoinMapper;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

@Authc
@RestController
@Log4j2
@RequestMapping("/mgr/art/expo")
@Api(tags = "ART_Mgr_展会管理")
public class ExpoMgrController {

    @Autowired
    private ExpoInfoService expoInfoService;

    @Autowired
    private ExpoJoinInfoService expoJoinInfoService;

    @Autowired
    private ExpoJoinMapper expoJoinMapper;

    @Autowired
    private ExpoSignUpInfoService expoSignUpInfoService;

    @Autowired
    private ExpoJoinProductInfoService expoJoinProductInfoService;

    //-------------------------------参展
    @PostMapping("/query")
    @ApiOperation(value = "查询", response = ExpoModel.class)
    public BaseResult query(@RequestBody ExpoQueryReq params) {
        IPage<ExpoInfo> page = expoInfoService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<ExpoInfo>()
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                        .eq(StrUtil.isNotEmpty(params.getName()), "name", params.getName())
                        .orderByDesc("orders")
        );
        IPage<ExpoModel> data = page.convert(new Function<ExpoInfo, ExpoModel>() {
            @Override
            public ExpoModel apply(ExpoInfo entity) {
                return ArtConvertUtils.getExpoModel(entity);
            }
        });
        return BaseResult.ok(data);
    }

    @GetMapping("/get")
    @ApiOperation(value = "详情", response = ExpoModel.class)
    public BaseResult get(@RequestParam("id") String id) {
        ExpoInfo entity = expoInfoService.getById(id);
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        ExpoModel data = ArtConvertUtils.getExpoModel(entity);
        return BaseResult.ok(data);
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增", response = BaseResult.class)
    @StaffLogc(title = "新增展会", action = "新增展会", actionAdo = "展会管理")
    public BaseResult save(@RequestBody ExpoAddParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        ExpoInfo entity = new ExpoInfo();
        entity.setId(IdUtil.getSnowflake(5, 1).nextIdStr());
        entity.setName(params.getName());
        entity.setImgs(params.getImgs());
        entity.setBanner(params.getBanner());
        entity.setRemark(params.getRemark());
        entity.setBizVal1(params.getBizVal1());
        entity.setBizVal2(params.getBizVal2());
        entity.setBizVal3(params.getBizVal3());
        entity.setBizVal4(params.getBizVal4());
        entity.setBizVal5(params.getBizVal5());
        if (CheckUtils.isEmpty(params.getOrders())) {
            entity.setOrders(0);
        } else {
            entity.setOrders(params.getOrders());
        }
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        expoInfoService.save(entity);
        return BaseResult.ok();
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改", response = BaseResult.class)
    @StaffLogc(title = "修改展会", action = "修改展会", actionAdo = "展会管理")
    public BaseResult update(@RequestBody ExpoEditParam params) {
        ExpoInfo entity = expoInfoService.getById(params.getId());
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        entity.setName(params.getName());
        entity.setImgs(params.getImgs());
        entity.setRemark(params.getRemark());
        entity.setBanner(params.getBanner());
        entity.setBizVal1(params.getBizVal1());
        entity.setBizVal2(params.getBizVal2());
        entity.setBizVal3(params.getBizVal3());
        entity.setBizVal4(params.getBizVal4());
        entity.setBizVal5(params.getBizVal5());
        entity.setOrders(params.getOrders());
        entity.addEditParam(userInfo);
        expoInfoService.updateById(entity);
        return BaseResult.ok();
    }

    @GetMapping("/delete")
    @ApiOperation(value = "删除")
    @StaffLogc(title = "删除展会", action = "删除展会", actionAdo = "展会管理")
    public BaseResult delete(@RequestParam("id") String id) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        ExpoInfo entity = expoInfoService.getById(id);
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        entity.setRowsState(BaseConstant.EnabledEnum.DISABLED.getCode());
        entity.addEditParam(userInfo);
        expoInfoService.updateById(entity);
        return BaseResult.ok();
    }


    //-------------------------------参展公司
    @PostMapping("/queryJoin")
    @ApiOperation(value = "查询参展公司", response = ExpoJoinCompanyModel.class)
    public BaseResult queryJoin(@RequestBody ExpoJoinQuery4PageParam params) {
        IPage<ExpoJoinCompanyModel> page = expoJoinMapper.queryExpoJoinCompany(
                new Page<ExpoJoinCompanyModel>(params.getPage(), params.getRows()),
                new QueryWrapper<ExpoJoinCompanyModel>()
                        .eq(StrUtil.isNotEmpty(params.getExpoNo()), "a.expo_no", params.getExpoNo())
                        .eq(StrUtil.isNotEmpty(params.getOrgNo()), "a.org_no", params.getOrgNo())
                        .eq(StrUtil.isNotEmpty(params.getBoothNo()), "a.booth_no", params.getBoothNo())
                        .eq(StrUtil.isNotEmpty(params.getState()), "a.state", params.getState())
                        .orderByDesc("a.orders")
        );
        return BaseResult.ok(page);
    }

    @GetMapping("/getJoin")
    @ApiOperation(value = "获取参展公司", response = ExpoJoinCompanyModel.class)
    public BaseResult getJoin(@RequestParam("id") Integer id) {
        if (CheckUtils.isEmpty(id)) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        List<ExpoJoinCompanyModel> list = expoJoinMapper.listExpoJoinCompany(
                new QueryWrapper<ExpoJoinCompanyModel>()
                        .eq("a.id", id));
        if (CollUtil.isEmpty(list)) {
            return BaseResult.ok();
        }
        return BaseResult.ok(list.get(0));
    }

    @PostMapping("/updateJoin")
    @ApiOperation(value = "修改参展公司", response = BaseResult.class)
    @StaffLogc(title = "修改参展公司", action = "修改参展公司", actionAdo = "展会管理")
    public BaseResult updateJoin(@RequestBody ExpoJoinCompanyEditParam params) {
        ValidatorUtils.validate(params);
        ExpoJoinInfo entity = expoJoinInfoService.getById(params.getId());
        if (entity == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if (StrUtil.isNotEmpty(params.getBoothNo())) {
            entity.setBoothNo(params.getBoothNo());
        }
        if (StrUtil.isNotEmpty(params.getBizVal())) {
            entity.setBizVal(params.getBizVal());
        }
        if (StrUtil.isNotEmpty(params.getState())) {
            entity.setState(params.getState());
        }
        if (CheckUtils.hasInt(params.getOrders())) {
            entity.setOrders(params.getOrders());
        }
        expoJoinInfoService.updateById(entity);
        return BaseResult.ok();
    }


    @PostMapping("/addJoin")
    @ApiOperation(value = "新增参展公司", response = BaseResult.class)
    @StaffLogc(title = "新增参展公司", action = "新增参展公司", actionAdo = "展会管理")
    public BaseResult addJoin(@RequestBody ExpoJoinCompanyAddParam params) {
        ValidatorUtils.validate(params);
        ExpoInfo entity = expoInfoService.getById(params.getExpoNo());
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        AtomicReference<String> orgNo= new AtomicReference<>("");
        params.getItems().forEach(item -> {
            orgNo.set(item.getOrgNo());
        });
        log.debug("+++++orgNo.get():",orgNo.get());
        int num =  expoJoinInfoService.count(new QueryWrapper<ExpoJoinInfo>()
                .eq("expo_no", params.getExpoNo())
                .eq("org_no",orgNo.get())
        );
        if (num > 0) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL.getCode(), "公司参加");
        }

        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        List<ExpoJoinInfo> joinInfos = new ArrayList<>();

        params.getItems().forEach(item -> {
            ExpoJoinInfo joinEntity = new ExpoJoinInfo();
            joinEntity.setExpoNo(params.getExpoNo());
            joinEntity.setOrgNo(item.getOrgNo());
            joinEntity.setBoothNo(item.getBoothNo());
            joinEntity.setBizVal(item.getBizVal());
            joinEntity.setState(item.getState());
            joinEntity.setOrders(item.getOrders());
            joinEntity.addCreateParam(userInfo);
            joinEntity.addEditParam(userInfo);
            joinInfos.add(joinEntity);
        });

        if (joinInfos.size() > 0) {
            expoJoinInfoService.saveBatch(joinInfos);
        }
        return BaseResult.ok();
    }


    @GetMapping("/delJoin")
    @ApiOperation(value = "删除参展公司", response = BaseResult.class)
    @StaffLogc(title = "删除参展公司", action = "删除参展公司", actionAdo = "展会管理")
    public BaseResult delJoin(@RequestParam("id") Integer id) {
        ExpoJoinInfo entity = expoJoinInfoService.getById(id);
        if (entity != null) {
            expoJoinInfoService.removeById(id);
        }
        return BaseResult.ok();
    }


    //-------------------------------参展公司商品
    @PostMapping("/queryJoinProduct")
    @ApiOperation(value = "查询展会参会公司商品", response = ExpoJoinProductModel.class)
    public BaseResult queryJoinProduct(@RequestBody ExpoJoinProductQuery4PageParam params) {
        ValidatorUtils.validate(params);
        IPage<ExpoJoinProductModel> page = expoJoinMapper.queryExpoJoinProduct(
                new Page<ExpoJoinProductModel>(1, 1000),
                new QueryWrapper<ExpoJoinProductModel>()
                        .eq(StrUtil.isNotEmpty(params.getExpoNo()), "b.expo_no", params.getExpoNo())
                        .eq(StrUtil.isNotEmpty(params.getPrdNo()), "b.prd_no", params.getPrdNo())
                        .eq(StrUtil.isNotEmpty(params.getOrgNo()), "b.org_no", params.getOrgNo())
//                .eq(CheckUtils.hasInt(params.getJoinId()),"b.join_id",params.getJoinId())
                        .orderByDesc("b.orders")
        );
        if (page == null) {
            return BaseResult.ok();
        }
        return BaseResult.ok(page.getRecords());
    }


    @PostMapping("/addJoinProduct")
    @ApiOperation(value = "新增展会参会公司商品", response = BaseResult.class)
    @StaffLogc(title = "新增展会参会公司商品", action = "新增展会参会公司商品", actionAdo = "展会管理")
    public BaseResult addJoinProduct(@RequestBody ExpoJoinProductAddParam params) {
        ValidatorUtils.validate(params);
        if (CollUtil.isEmpty(params.getItems())) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }

        Set<String> works = new HashSet<>();
        params.getItems().forEach(item -> {
            works.add(item.getPrdNo());
        });
        int num = expoJoinProductInfoService.count(new QueryWrapper<ExpoJoinProductInfo>()
                .eq("expo_no", params.getExpoNo())
                .in("prd_no", works)
        );
        if (num > 0) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL.getCode(), "新增的作品展会已存在，请检查后在添加");
        }

        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        List<ExpoJoinProductInfo> list = new ArrayList<>();

        params.getItems().forEach(item -> {
            ExpoJoinProductInfo entity = new ExpoJoinProductInfo();
            entity.setJoinId(-1);
            entity.setExpoNo(params.getExpoNo());
            entity.setOrgNo(params.getOrgNo());
            entity.setPrdNo(item.getPrdNo());
            if (item.getOrders() != null) {
                entity.setOrders(item.getOrders());
            }
            entity.setRemark(item.getRemark());
            entity.addCreateParam(userInfo);
            entity.addEditParam(userInfo);
            list.add(entity);
        });
        if (list.size() > 0) {
            expoJoinProductInfoService.saveBatch(list);
        }
        return BaseResult.ok();
    }


    @PostMapping("/updateJoinProduct")
    @ApiOperation(value = "修改展会参会公司商品", response = BaseResult.class)
    @StaffLogc(title = "修改展会参会公司商品", action = "修改展会参会公司商品", actionAdo = "展会管理")
    public BaseResult updateJoinProduct(@RequestBody ExpoJoinProductEditParam params) {
        ValidatorUtils.validate(params);
        ExpoJoinProductInfo entity = expoJoinProductInfoService.getById(params.getId());
        if (entity == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        entity.setExpoNo(params.getExpoNo());
        entity.setOrgNo(params.getOrgNo());
        entity.setPrdNo(params.getPrdNo());
        if (CheckUtils.hasInt(params.getOrders())) {
            entity.setOrders(params.getOrders());
        }
        entity.setRemark(params.getRemark());
        expoJoinProductInfoService.updateById(entity);
        return BaseResult.ok();
    }

    @PostMapping("/delJoinProduct")
    @ApiOperation(value = "删除展会参会公司商品", response = BaseResult.class)
    @StaffLogc(title = "删除展会参会公司商品", action = "删除展会参会公司商品", actionAdo = "展会管理")
    public BaseResult delJoinProduct(@RequestBody ExpoJoinProductDelParam params) {
        ValidatorUtils.validate(params);
        if (CollUtil.isEmpty(params.getIds())) {
            return BaseResult.ok();
        }
        expoJoinProductInfoService.removeByIds(params.getIds());
        return BaseResult.ok();
    }


    //-------------------------------报名
    @PostMapping("/querySignUp")
    @ApiOperation(value = "查询展会报名", response = ExpoSignUpModel.class)
    public BaseResult querySignUp(@RequestBody ExpoSignUpQueryPage4Param params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        IPage<ExpoSignUpInfo> page = expoSignUpInfoService.page(
                new Page<ExpoSignUpInfo>(params.getPage(), params.getRows()),
                new QueryWrapper<ExpoSignUpInfo>()
                        .eq(StrUtil.isNotEmpty(params.getExpoNo()), "expo_no", params.getExpoNo())
                        .eq(StrUtil.isNotEmpty(params.getBoothNo()), "booth_no", params.getBoothNo())
                        .eq(StrUtil.isNotEmpty(params.getState()), "state", params.getState())
                        .eq(CheckUtils.hasInt(params.getUserId()), "user_id", params.getUserId())
                        .orderByDesc("cdt")
        );
        if (page == null || CollUtil.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }
        Set<String> expoNos = new HashSet<>();
        page.getRecords().forEach(item -> {
            expoNos.add(item.getExpoNo());
        });
        List<ExpoInfo> expoList = expoInfoService.listByIds(expoNos);
        IPage<ExpoSignUpModel> data = page.convert(new Function<ExpoSignUpInfo, ExpoSignUpModel>() {
            @Override
            public ExpoSignUpModel apply(ExpoSignUpInfo entity) {
                return ArtConvertUtils.getExpoSignUpModel(entity, expoList);
            }
        });
        return BaseResult.ok(data);
    }

    @GetMapping("/getSignUp")
    @ApiOperation(value = "获取展会报名", response = ExpoSignUpModel.class)
    public BaseResult getSignUp(@RequestParam("id") Integer id) {
        ExpoSignUpInfo entity = expoSignUpInfoService.getById(id);
        if (entity == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        ExpoInfo expoInfo = expoInfoService.getById(entity.getExpoNo());
        ExpoSignUpModel data = ArtConvertUtils.getExpoSignUpModel(entity);
        data.setExpoName(expoInfo.getName());
        return BaseResult.ok(data);
    }

    @PostMapping("/updateSignUp")
    @ApiOperation(value = "修改展会报名", response = BaseResult.class)
    public BaseResult updateSignUp(@RequestBody ExpoSignUpUpdateParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        ExpoSignUpInfo entity = expoSignUpInfoService.getById(params.getId());
        if (entity == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if (StrUtil.isNotEmpty(params.getBoothNo())) {
            entity.setBoothNo(params.getBoothNo());
        }
        if (StrUtil.isNotEmpty(params.getState())) {
            entity.setState(params.getState());
        }
        entity.addEditParam(userInfo);
        expoSignUpInfoService.updateById(entity);
        return BaseResult.ok();
    }


}
